<template>
  <!--  发货区域，支持选择快递-->
  <j-modal
    switchFullscreen
    width="60%"
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-form :form="form">
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="经销商名称"
          >
            <a-input-search v-decorator="['custName',validatorRules.custName]" placeholder="请选择经销商名称"
                            @click="custSearch('custname')"     readOnly :disabled="disableSubmits" enter-button @search="custSearch('custname')" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="经销商编号"
            hasFeedback
          >
            <a-input :disabled="true" placeholder="请选择经销商名称"
                     @click="custSearch('custname')"     v-decorator="['custCode',validatorRules.custCode]"></a-input>
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="送达方"
          >
            <a-input-search placeholder="请选择送达方" v-decorator="['kunwe',validatorRules.kunwe]"
                       @click="policyTag()"     readOnly :disabled="disableSubmits" enter-button @search="policyTag()" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="送达方地址"
            hasFeedback>
            <a-input readOnly placeholder="请选择送达方"  @click="policyTag()"   v-decorator="['kunweName', validatorRules.kunweName]"/>
            <!--          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'punchTime', {}]" />-->
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="省/市/区"
        >
          <cn-area-linkage
            @change="areaChange"
            v-model="areaLinkage"
            type="cascader"
            :province.sync="province"
            :city.sync="city"
            :area.sync="area"
          />
        </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="详细地址"
            hasFeedback>
            <a-input placeholder="请输入详细地址" v-decorator="['address', validatorRules.address]"/>
            <!--          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'punchTime', {}]" />-->
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="联系人"
            hasFeedback
          >
            <a-input placeholder="请输入" type="linkman" :disabled="disableSubmit" @change="e => priceCh(e)" v-decorator="['linkman',validatorRules.linkman]"></a-input>
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="联系电话"
            hasFeedback>
            <a-input placeholder="请输入联系电话" v-decorator="['telephone', validatorRules.telephone]"/>
            <!--          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'punchTime', {}]" />-->
          </a-form-item>
        </a-col>


        <a-col :md="12" :sm="24">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否默认地址"
        >
          <cn-dict-select-tag
            placeholder="请选择是否默认地址"
            :triggerChange="true"
            dictCode="yesOrNo"
            v-decorator="['defaultStatus', validatorRules.defaultStatus]"
            :options="{
              value:'dictDataCode',
              label:'dictDataDesc'
            }"
          />
        </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="备注"
            hasFeedback>
            <a-input placeholder="请输入备注" v-decorator="['remarks', validatorRules.remarks]"/>
            <!--          <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'punchTime', {}]" />-->
          </a-form-item>
        </a-col>



        <!--        <a-col :md="12" :sm="24">-->
        <!--          <a-form-item-->
        <!--            :labelCol="labelCol"-->
        <!--            :wrapperCol="wrapperCol"-->
        <!--            label="erp凭证码"-->
        <!--            hasFeedback-->
        <!--          >-->
        <!--            <a-input placeholder="请输入erp凭证码" :disabled='disableSubmit'-->
        <!--                     v-decorator="['erpKey',validatorRules.erpKey]"></a-input>-->
        <!--          </a-form-item>-->
        <!--        </a-col>-->
      </a-row>
    </a-form>
    <policys ref="policysModal" v-bind="policysData" @polocyOk="polocyOk"></policys>
    <proChose ref="prochoose" v-bind="modalProps" @okbro="okbropro"></proChose>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import proChose from '@comp/cn-components/ProChose'
import policys from '@comp/cn-components/Policys'
import { pick } from 'lodash'
import { isMobile } from '@/utils/validate'
import Area from '@comp/utils/Area'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'

export default {
  name: 'priceAdd',
  components: {
    proChose,
policys,
    JAreaLinkage
  },
  data() {
    return {
      areaLinkage: "",
      name:'',
      province: "",
      city: "",
      area: "",
      disableSubmit: false,
      disableSubmits: false,
      title: '',
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      url: {
        // kuaidi: window._CONFIG['domianOrderURL'] + '/cnDictionaryTypeController/getDictionaryTypeList'
        sendOrder: window._CONFIG['domianURL'] + '/cnShippingAddressController/saveOrUpdateEntity'
      },
      validatorRules: {
        address: {
          rules: [
            { required: true, message: '' }
          ]
        },
        linkman: {
          rules: [
            { required: true, message: '' }
          ]
        },
        custCode: {
          rules: [
            { required: true, message: '' }
          ]
        },
        custName: {
          rules: [
            { required: true, message: '' }
          ]
        },
        telephone: {
          rules: [
            { required: true, message: '', trigger: 'submit' },
            {
              validator: function(rule, value, callback) {
                if (!isMobile(value)) {
                  callback(new Error(''))
                }
                callback()
              }
            }
          ]
        },
      },
      modal: undefined
    }
  },

  methods: {
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area();
      }},
    areaChange(code) {
      let cities = this.areaData.getText(code,'多个值').cities
      let codes = this.areaData.getText(code,'多个值').codes
      this.model.province = cities.split('/')[0]
      this.model.city = cities.split('/')[1]
      this.model.area = cities.split('/')[2]
      this.model.provinceCode = this.dealCode(codes.split('/')[0],2).join('')
      this.model.cityCode = this.dealCode(codes.split('/')[1],4).join('')
      this.model.areaCode = this.dealCode(codes.split('/')[2],6).join('')
      console.log(this.model)
    },
    // params:code:编号，count位数
    dealCode(code,count){
      console.log(code)
      let num = code.split('')
      let codes = []
      for(let i = 0;i<count;i++){
        codes.push(num[i])
      }
      return codes
    },
    polocyOk(e1,e2){
      if(e1.length !==0){
        this.form.setFieldsValue({
          kunwe:e1[0].kunwe,
          kunweName:e1[0].kunweName,

        })
      }
    },
    policyTag() {
      let code = this.form.getFieldValue('custCode')
        if(!code){
          this.$message.info('请先选择经销商')
          return
      }
      let params = {
        custCode: code
      }
      this.$refs.policysModal.edit(params,'kunwe')
    },
    priceCh(e){
      console.log(e.target.value)
      let num = e.target.value
      if(num < 0){
      this.$nextTick(()=>{
        this.form.setFieldsValue({
          price:0
        })
      })
      }
    },
    custSearch(status) {
      this.$refs.prochoose.rowKey='custCode'
      let formconfig = [
        {
          key: 'custCode',
          label: '经销商编号'
        },
        {
          key: 'custName',
          label: '经销商名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '经销商编号',
            align: 'center',
            dataIndex: 'custCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'custName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/customerController/getPageList',
        multiple: false,
        columW: 8
      }
      let dataSource = []
      if(this.form.getFieldValue('custCode')){
        dataSource = [{
          custCode:this.form.getFieldValue('custCode'),
          custName:this.form.getFieldValue('custName')
        }]
      }
      this.name = '经销商'
      this.$refs.prochoose.edit(formconfig, tableconfig, status,'status2',dataSource)
    },
    productSearch(status) {
      let formconfig = [
        {
          key: 'productCode',
          label: '商品编号'
        },
        {
          key: 'productName',
          label: '商品名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '商品编号',
            align: 'center',
            dataIndex: 'productCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '商品名称',
            align: 'center',
            dataIndex: 'productName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnProductController/getProductListByCust',
        multiple: false,
        columW: 8
      }
      this.name = '商品'
      this.$refs.prochoose.edit(formconfig, tableconfig, status)
    },
    okbropro(record, status) {
      console.log(record,status)
      let res = record[0]
      if (status == 'product') {
        this.form.setFieldsValue(pick(res, 'productCode', 'productName'))
      } else {
        this.form.setFieldsValue(pick(res, 'custCode', 'custName',))
        console.log(this.form.getFieldValue('channelName'))
      }

    },
    add(record, status) {
      this.edit(record, status)
    },
    edit(iscord) {
      console.log(iscord)
      this.disableSubmits = false
      this.form.resetFields()
      this.model = {}
      this.modal = undefined
      this.visible = true
      if (typeof iscord !== 'undefined') {
        this.modal = Object.assign({}, iscord)
        let pca = this.modal.province + "/" + this.modal.city + "/" + this.modal.area;
        this.areaLinkage = this.areaData.getAreaCodeByText(pca) || "";
        this.disableSubmits = true
        this.$nextTick(() => {
          this.form.setFieldsValue({ ...this.modal })
        })
      }
    },
    handleOk() {
      let _vm = this
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          this.modal == undefined ? console.log('新增提交') : values.id = this.modal.id
          values = Object.assign({},this.model,values)
          postAction(this.url.sendOrder, values).then(res => {
            if (!res.success) {
              this.$message.error(res.message)
            } else {
              this.$emit('ok')
            }
            _vm.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.confirmLoading = false
    },
    close() {
      this.handleCancel()
    }
  },
  computed:{
    policysData() {
      return {
        title: '送达方',
        width: `${50}%`,
        rowKey: 'kunwe',
        way: 'post',
        tableUrl: window._CONFIG['domianURL'] + '/cnShippingKunwe/getByCustCode',
        tableColums: [
          {
            title: '送达方',
            align: 'center',
            dataIndex: 'kunwe'
          },
          {
            title: '送达方地址',
            align: 'center',
            dataIndex: 'kunweName'
          }
        ],
        multiple: false

      }
    },
    modalProps(){
      return Object.assign({},{
        name:this.name
      })
    }
  },
created(){
    this.initAreaData()
},
}
</script>

<style scoped>

</style>